<?php 

	/**
	 * @package Yomm
	 * @author bsuter
	 *
	 */
	Class Yomm_Library_CmsTools	{
		
		static public $letters = array('a','b','c','d','e','f','g','h','k','m','n','o','p','q','r','s','t','u','v','w');
		
		static function ReaddirRecursive($start_dir)
		{
			$files = array();
			
			if(!is_dir($start_dir))
			{
				return false;
			}
			
			$fh = opendir($start_dir);
			
			while(($file = readdir($fh)) !== false) 
			{
				if(strcmp($file, '.') == 0 || strcmp($file, '..') == 0 || ( substr($file, 0, 1) == "." )) continue;
				
				$filepath = $start_dir . '/' . $file;
				
				if (is_dir($filepath))
				{
					$files = array_merge($files, Tools::ReaddirRecursive($filepath));
				} else {
					array_push($files, $filepath);
				}
			}
				
			closedir($fh);
			
			return $files;
		}
		
		static function BuildLinkByRewrite($rewrite)
		{
			$db = Yomm_Db_Query::getInstance();
			
			$obj = $db->select("cms_nav", array(
				"cms_block.rewrite_link" => "block_rw",
				"cms_language.i18n" => "lang",
				"cms_cat.rewrite_link" => "cat_rw"
			), "LEFT JOIN (cms_cat, cms_block LEFT JOIN (cms_language) ON (cms_language.id=cms_block.language_id)) ON (cms_cat.id = cms_nav.cat AND cms_block.nav_id = cms_nav.id) WHERE cms_block.rewrite_link='{$rewrite}' AND cms_nav.del=0", false);
			
			if(count($obj) !== 1)
			{
				throw new Yomm_Error("The requested Link '$rewrite' in Tools::BuildLInkByRewrite is not valid and returns an sql_numrows value of: " . count($obj));
				return SiteConfig::Domain;
			}
			
			return Tools::BuildLinkByParts($obj->block_rw, $obj->lang, $obj->cat_rw);
		}
		
		static function BuildLinkById($nav_id)
		{
			$db = ydsql::getInstance();
			
			$obj = $db->select("cms_nav", array(
				"cms_block.rewrite_link" => "block_rw",
				"cms_language.i18n" => "lang",
				"cms_cat.rewrite_link" => "cat_rw"
			), "LEFT JOIN (cms_cat, cms_block LEFT JOIN (cms_language) ON (cms_language.id=cms_block.language_id)) ON (cms_cat.id = cms_nav.cat AND cms_block.nav_id = cms_nav.id) WHERE cms_nav.id={$nav_id} AND cms_language.i18n='{$_SESSION['i18n']}' AND cms_nav.del=0", false);
			
			return Tools::BuildLinkByParts($obj->block_rw, $obj->lang, $obj->cat_rw);
		}
		
		static function BuildLinkByParts($rewrite_name, $i18n_tag, $rewrite_cat)
		{
			if(SiteConfig::RewriteLinks === true)
			{
				$link = SiteConfig::Domain;
				
				// TODO: delete this in first release
				if(!defined('SiteConfig::RewriteLinksDisplayLang')) // throw initial error
				{
					echo "SiteConfig::RewriteLinksDisplayLang not defined!"; exit;
				}
				
				// if DisplayLang is true; add into rewrite link
				if(SiteConfig::RewriteLinksDisplayLang === true)
				{
					$link = SiteConfig::Domain . $i18n_tag . '/';
				}
				
				// if DisplayCat is true; add into rewrite link
				if(SiteConfig::RewriteLinksDisplayCat === true) {
					$link.= $rewrite_cat . '/';
				}
				
				// new: without .html just trailing slash
				$link.= $rewrite_name; // .'.html';
				
			} else {
				$link = SiteConfig::Domain . '?i18n=' . $i18n_tag . '&page=' . $rewrite_name . '&cat=' . $rewrite_cat;
			}
			
			return $link;
		}
		
		static function RandomHash()
		{
			return (Tools::RandomString(15) . session_id());
		}
		
		static public function RandomString($chars = 15)
		{
			$str = null;
			for($i=1; $i<=$chars; $i++)
			{
				$str .= self::$letters[rand(1,(count(self::$letters)-1))];
			}
			return $str;
		}
		
		
		/*
		static public function ArrayToObject($array)
		{
			if(!is_array($array) || count($array) == 0) return $array;
			
			$return = new stdClass();
			
			foreach ($array as $k => $v)
			{
				if (is_array($v))
				{
					$return->$k = Tools::ArrayToObject($v);
				}
				else {
					$return->$k = $v;
				}
			}
		 
			return $return;
		}
		
		
		static public function ObjectToArray($obj)
		{ 
			if(!is_object($obj) || is_null($obj)) return $obj;
			
		    $_arr = is_object($obj) ? get_object_vars($obj) : $obj; 
		    foreach ($_arr as $key => $val)
		    { 
		        $val = (is_array($val) || is_object($val)) ? Tools::ObjectToArray($val) : $val; 
		        $arr[$key] = $val; 
		    } 
		    return $arr; 
		}
		*/
		
		static public function BrowserInfo($agent = null) {
			// Declare known browsers to look for
			$known = array('msie', 'firefox', 'safari', 'webkit', 'opera', 'netscape', 'konqueror', 'gecko');
			
			// Clean up agent and build regex that matches phrases for known browsers
			// (e.g. "Firefox/2.0" or "MSIE 6.0" (This only matches the major and minor
			// version numbers.  E.g. "2.0.0.6" is parsed as simply "2.0"
			$agent = strtolower($agent ? $agent : $_SERVER['HTTP_USER_AGENT']);
			
			$pattern = '#(?<browser>' . join('|', $known) .
			  ')[/ ]+(?<version>[0-9]+(?:\.[0-9]+)?)#';
			 // Find all phrases (or return empty array if none found)
			if (!preg_match_all($pattern, $agent, $matches)) return array();
			// Since some UAs have more than one phrase (e.g Firefox has a Gecko phrase,
			// Opera 7,8 have a MSIE phrase), use the last one found (the right-most one
			// in the UA).  That's usually the most correct.
			$i = count($matches['browser'])-1;
			return array($matches['browser'][$i] => $matches['version'][$i]);
		}
		
		static public function downloadAndStore($http_url, $local_url)
		{
			$old_umask = umask(0);
			
			$file_content = null;
			
			if(function_exists('curl_init')) $curl = true;
			
			if(isset($curl))
			{
				
				$ch = curl_init();
				curl_setopt($ch, CURLOPT_URL, $http_url);
				curl_setopt($ch, CURLOPT_HEADER, false);
				curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
				$file_content = curl_exec($ch);
				curl_close($ch);
			}
			
			if(is_null($file_content))
			{
				if((bool)ini_get('allow_url_fopen'))
				{
					$file_content = file_get_contents($http_url, "r");
				}
			}
			if(is_null($file_content))
				return false;
			
			// 0644	
				
			/*$fp = fopen(, 'w');
			fwrite($fp, $file_content);
			fclose($fp);
			*/
			
			$new_file = $local_url . pathinfo($http_url, PATHINFO_BASENAME);
			
			
	        // remove original file
	        if (file_exists($new_file))
	            @unlink($new_file); 
			
			if (!file_put_contents($new_file, $file_content)) {
	            umask($old_umask);
	            throw new Yomm_Error("unable to write file {$new_file}");
	            return false;
	        }
			
	        // set file permissions
	        @chmod($new_file, 0644);
	        umask($old_umask);
	        
	        
	        
			return $local_url . pathinfo($http_url, PATHINFO_BASENAME);
			
		}
		
		static public function unzip($zip_file_src)
		{
			$old_umask = umask(0);
			
			$zip = zip_open($zip_file_src);
			
			$i=0;
			
			define('PKG_DIR', pathinfo($zip_file_src, PATHINFO_DIRNAME) . '/');
			
			while($zip_entry = zip_read($zip))
			{
				$i++;
				
				$entry = zip_entry_open($zip,$zip_entry);
				$filename = zip_entry_name($zip_entry);
				
				//$target_dir = AVAMODULEROOT . substr($filename,0,strrpos($filename,'/'));
				
				$target_dir =  PKG_DIR . substr($filename,0,strrpos($filename,'/'));
				
				if ( $i == 1 ) {
					$first_dir = $target_dir;
					$zip_folder = substr($filename,0,strrpos($filename,'/'));
				}
				
				$filesize = zip_entry_filesize($zip_entry);
				if (is_dir($target_dir) || mkdir($target_dir))
				{
					if ($filesize > 0)
					{
						$contents = zip_entry_read($zip_entry, $filesize);
						
						 // remove original file
				        if (file_exists(PKG_DIR . $filename))
				            @unlink(PKG_DIR . $filename); 
				            
						if (!file_put_contents(PKG_DIR . $filename, $contents)) {
				            umask($old_umask);
				            throw new Yomm_Error("unable to write file {$filename}");
				            return false;
				        }
				        
				        @chmod(PKG_DIR . $filename, Yomm_Config::VAR_FILE_PERMISSION);
	       				umask($old_umask);
					}
				}
			}
			
			$target_dir = $first_dir;
			
			return array($first_dir, $zip_folder);
		}
		
		// TODO: DELETE CmsTools class for usage of this method in other classes!
		static public function moveFile($from_path, $to_path, $over_write = false)
		{
			if(file_exists($to_path) && $over_write === false)
			{
				throw new Yomm_Error("the file '{$to_path}' is already existing and over_write is false");
				return false;
			}
			
			$old_umask = umask(0);
			rename($from_path, $to_path);
        	@chmod($to_path, Yomm_Config::VAR_FILE_PERMISSION);
        	umask($old_umask);
        	
        	return;
		}
		
		// TODO: DELETE CmsTools class for usage of this method in other classes!
		static public function copyFile($from_path, $to_path, $over_write = false)
		{
			if(file_exists($to_path) && $over_write === false)
			{
				throw new Yomm_Error("the file '{$to_path}' is already existing and over_write is false");
				return false;
			}
			
			$old_umask = umask(0);
			copy($from_path, $to_path);
        	@chmod($to_path, Yomm_Config::VAR_FILE_PERMISSION);
        	umask($old_umask);
        	
        	return;
		}
		
		// TODO: DELETE CmsTools class for usage of this method in other classes!
		static public function createFile($file_save_path, $file_content)
		{
			$old_umask = umask(0);
			
			$_tmp_file = tempnam(Yomm_Config::DIR_CACHE, 'tplfilecache');
			
			if(!file_put_contents($_tmp_file, $file_content))
			{
				umask($old_umask);
				throw new Yomm_Error("unable to write content into file {$_tmp_file}");
				return false;
			}
			
			if(file_exists($file_save_path))
			{
				unlink($file_save_path);
			}
			
			if(@rename($_tmp_file, $file_save_path) === false)
			{
				unlink($_tmp_file);
				throw new Yomm_Error("unable to rename {$_tmp_file} into {$file_save_path}");
				return false;	
			}
			
			
			
			// set the new permissions
			chmod($file_save_path, Yomm_Config::VAR_FILE_PERMISSION);
			umask($old_umask);
			
			return true;
		}
		
		// TODO: DELETE CmsTools class for usage of this method in other classes!
		/*
		 * NO TRAILING SLASH!
		 */
		static public function createDir($dir)
		{
			$old_umask = umask(0);
			
			$tc_dir = pathinfo($dir, PATHINFO_DIRNAME);
			
			if(!is_writable($tc_dir))
			{
				if(!@chmod($tc_dir, Yomm_Config::VAR_DIR_PERMISSION));
					return false;
			}
			
			mkdir($dir, Yomm_Config::VAR_DIR_PERMISSION);
			@chmod($dir, Yomm_Config::VAR_DIR_PERMISSION);
			umask($old_umask);
			
			return true;
		}
		
		static public function debugLocaleconv()
		{
			print getenv("LANG");
			print $_ENV['LANG'];
			print "calling localeconv() directly\n";
			print_r(localeconv());
			printf("%f",-123.456);
			print "\ncalling setlocale() before localeconv()\n";
			print(setlocale(LC_ALL,null));
			print_r(localeconv());
			printf("%f",-123.456);
		}
	}